package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.ActionBar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.Base;
import com.isunland.managesystem.base.BaseNetworkDialogFragment;
import com.isunland.managesystem.base.BaseTimeDialogFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.base.BaseYMDTimeDialogFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.CustomerDialog;
import com.isunland.managesystem.entity.DataStatus;
import com.isunland.managesystem.entity.LeaseMainList;
import com.isunland.managesystem.entity.PayAndBackParams;
import com.isunland.managesystem.utils.MyDateUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ParamsNotEmpty;
import com.isunland.managesystem.utils.SharedPreferencesUtil;
import com.isunland.managesystem.utils.ToastUtil;
import com.isunland.managesystem.widget.SingleLineView;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;
import org.json.JSONException;

/**
 * 对象功能: 添加预约订单
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: wangyanan
 * 创建时间: 2017/1/5 21:08
 */

public class LeaseOrderUpdateFragment extends Fragment {
  public static final String EXTRA_DETAIL =
      LeaseOrderUpdateFragment.class.getSimpleName() + ".EXTRA_DETAIL";
  public static final int REQUEST_SYS_ORG = 7;
  //public static final int REQUEST_OPERATION_TIME = 1;
  private static final int TYPE_SAVE = 2;
  private static final int TYPE_SUBMIT = 3;
  private static final int REQUEST_PAY = 4;
  private static final int REQUEST_DATE = 5;
  private static final int REQUEST_EQUIP = 6;
  //@BindView(R.id.tv_leaseOrganizationColon)
  //EditText tvLeaseOrganizationColon;
  @BindView(R.id.sl_leaseOrganizationColon) SingleLineView slLeaseOrganizationColon;

  @BindView(R.id.tv_leasePersonColon) EditText tvLeasePersonColon;
  @BindView(R.id.tv_customerAccountColon) EditText tvCustomerAccountColon;
  @BindView(R.id.tv_identityCardColon) EditText tvIdentityCardColon;
  @BindView(R.id.tv_contacts) EditText tvContacts;
  @BindView(R.id.tv_contactPhone) EditText tvContactPhone;
  @BindView(R.id.tv_leaseIntroductionColon) EditText tvLeaseIntroductionColon;
  @SuppressWarnings("all") @BindView(R.id.tv_leaseEquipmentDetail) TextView tvLeaseEquipmentDetail;
  @BindView(R.id.tv_totalDepositColon) EditText tvTotalDepositColon;
  @BindView(R.id.tv_totalLeaseColon) EditText tvTotalLeaseColon;
  @BindView(R.id.tv_customerAccountNo) EditText tvCustomerAccountNo;
  @BindView(R.id.tv_leaseDate) TextView tvLeaseDate;
  //public static final int REQUEST_TYPE = 2;
  //public static final int REQUEST_OBJECT = 3;

  private BaseVolleyActivity mActivity;
  //private Date mStartTime;
  private FragmentManager mFm;
  private LeaseMainList mItem;
  private String mId;
  private String status;
  private CurrentUser mCurrentUser;
  private String orgCode;
  /** 订单编号 */
  private String mLeaseNo;
  //private BaseSelectObject mObject;
  //private BaseSelectObject mType;

  public static Fragment newInstance(LeaseMainList item) {
    LeaseOrderUpdateFragment fragment = new LeaseOrderUpdateFragment();
    Bundle args = new Bundle();
    args.putSerializable(EXTRA_DETAIL, item);
    fragment.setArguments(args);
    return fragment;
  }

  public void onCreate(Bundle savedInstanceState) {
    setHasOptionsMenu(true);
    mItem = (LeaseMainList) getArguments().getSerializable(EXTRA_DETAIL);
    mActivity = (BaseVolleyActivity) getActivity();
    mCurrentUser = CurrentUser.newInstance(mActivity);
    mFm = mActivity.getSupportFragmentManager();
    ActionBar actionBar = mActivity.getSupportActionBar();
    if (actionBar != null) {
      actionBar.setDisplayHomeAsUpEnabled(true);
      if (mItem == null) {
        actionBar.setTitle(R.string.addOrder);
        mId = UUID.randomUUID().toString();
        status = DataStatus.NEW;
        mLeaseNo = MyDateUtil.getOrderNo();
      } else {
        actionBar.setTitle(R.string.modifyOrder);
        mId = mItem.getId();
        status = mItem.getDataStatus();
        mLeaseNo = mItem.getLeaseNo();
      }
    }
    super.onCreate(savedInstanceState);
  }

  //private void initView(View v) {
  //    tvOperationLocation.setEnabled(true);
  //    tvOperationLocation.setHint(R.string.hintInput);
  //    tvLandArea.setEnabled(true);
  //    tvLandArea.setHint(R.string.hintInput);
  //    tvOperationTime.setHint(R.string.hintSelect);
  //    //tvType.setHint(R.string.hintSelect);
  //    //tvObject.setHint(R.string.hintSelect);
  //    tvContacts.setEnabled(true);
  //    tvContacts.setHint(R.string.hintInput);
  //    tvContactPhone.setEnabled(true);
  //    tvContactPhone.setHint(R.string.hintInput);
  //}

  //初始化界面
  @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
      @Nullable Bundle savedInstanceState) {

    View v = inflater.inflate(R.layout.fragment_lease_order_update, container, false);
    ButterKnife.bind(this, v);
    bindData(mItem);
    //添加
    slLeaseOrganizationColon.setOnClickContentListener(new View.OnClickListener() {

      @Override public void onClick(View v) {
        DialogFragment dialog = new SysOrgDialogFragment();
        dialog.setTargetFragment(LeaseOrderUpdateFragment.this, REQUEST_SYS_ORG);
        dialog.show(mFm, "");
      }
    });
    return v;
  }

  private void bindData(LeaseMainList data) {
    if (data == null) {
      tvCustomerAccountNo.setText(mCurrentUser.getName());

      //slLeaseOrganizationColon.setTextContent();
      tvLeasePersonColon.setText(mCurrentUser.getRealName());
      //noinspection deprecation
      tvLeaseDate.setText(MyDateUtil.parseDateToString(new Date()));
      return;
    }
    //修改
    slLeaseOrganizationColon.setTextContent(data.getLeaseOrgName());
    orgCode = data.getLeaseOrgCode();
    tvLeasePersonColon.setText(data.getLeaseStaffName());
    tvCustomerAccountColon.setText(data.getCustomerAccount());
    tvCustomerAccountNo.setText(data.getCustomerAccountNo());
    //noinspection deprecation
    tvLeaseDate.setText(MyDateUtil.parseDateToString(MyDateUtil.stringToDate(data.getLeaseDate())));
    tvIdentityCardColon.setText(data.getIdCard());
    tvContacts.setText(data.getLinkman());
    tvContactPhone.setText(data.getLinkmanPhone());
    tvLeaseIntroductionColon.setText(data.getLeaseText());
    tvTotalDepositColon.setText(String.valueOf(data.getTotalPayDeposit()));
    tvTotalLeaseColon.setText(String.valueOf(data.getTotalPayLeaseMoney()));
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    inflater.inflate(R.menu.menu_order_save_submit, menu);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    //if (item == null) return super.onOptionsItemSelected(item);
    switch (item.getItemId()) {
      case android.R.id.home:
        getActivity().finish();
        return true;
      case R.id.menu_item_save:
        volleyPostSave(TYPE_SAVE);
        return true;
      case R.id.menu_item_submit:
        volleyPostSave(TYPE_SUBMIT);
        //PayAndBackActivity.newInstance(this,mActivity,mId,REQUEST_PAY);
        return true;
    }

    return super.onOptionsItemSelected(item);
  }

  private void volleyPostSave(final int type) {
    if (TextUtils.isEmpty(mId)) return;

    String org = slLeaseOrganizationColon.getTextContent();
    String person = tvLeasePersonColon.getText().toString().trim();
    String customer = tvCustomerAccountColon.getText().toString().trim();
    String customerNo = tvCustomerAccountNo.getText().toString().trim();
    String leaseDate = tvLeaseDate.getText().toString().trim();
    String idCard = tvIdentityCardColon.getText().toString().trim();
    String contact = tvContacts.getText().toString().trim();
    String contactPhone = tvContactPhone.getText().toString().trim();
    String introduction = tvLeaseIntroductionColon.getText().toString().trim();
    final String totalDeposit = tvTotalDepositColon.getText().toString().trim();
    final String totalLease = tvTotalLeaseColon.getText().toString().trim();

    boolean isComplete =

        !TextUtils.isEmpty(org)
            && !TextUtils.isEmpty(person)
            && !TextUtils.isEmpty(customer)
            && !TextUtils.isEmpty(customerNo)
            && !TextUtils.isEmpty(idCard)
            && !TextUtils.isEmpty(contact)
            && !TextUtils.isEmpty(contactPhone)
            && !TextUtils.isEmpty(introduction)
            && !TextUtils.isEmpty(totalDeposit)
            && !TextUtils.isEmpty(leaseDate)
            && !TextUtils.isEmpty(totalLease);

    if (!isComplete) {
      ToastUtil.show("请填写完整!");
      return;
    }

    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_LEASE_UPDATE);
    //HashMap<String, String> params = new HashMap<>();
    ParamsNotEmpty params = new ParamsNotEmpty();

    params.put("id", mId);
    params.put("leaseNo", mLeaseNo);
    params.put("leaseOrgName", org);
    params.put("leaseOrgCode", orgCode);
    params.put("leaseStaffName", person);
    params.put("dataStatus", "new");
    //noinspection deprecation
    params.put("leaseDate",
        MyDateUtil.parseTimeToString(MyDateUtil.stringToDate(leaseDate, MyDateUtil.TYPE_DATE)));
    params.put("linkman", contact);
    params.put("linkmanPhone", contactPhone);
    params.put("idCard", idCard);
    params.put("leaseText", introduction);
    params.put("totalPayDeposit", totalDeposit);
    params.put("totalPayLeaseMoney", totalLease);
    params.put("customerAccount", customer);
    params.put("customerAccountNo", customerNo);

    MyUtils.showDialogLoading(mActivity);
    mActivity.volleyPost(url, params.getParams(), new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {
        ToastUtil.show("保存失败!");
      }

      @Override public void onVolleyResponse(String json) throws JSONException {
        //json = MyUtils.readAssetsFile(MyApplication.getAppContext(), "testOperationDetail.json");
        Base original = new Gson().fromJson(json, Base.class);
        if (original != null && original.getResult() == Base.SUCCESS) {
          ToastUtil.show("保存成功");
          mActivity.setResult(Activity.RESULT_OK);
          if (type == TYPE_SAVE) {
            mActivity.finish();
          }
          if (type == TYPE_SUBMIT) {
            String totalDeposit = tvTotalDepositColon.getText().toString().trim();
            String totalLease = tvTotalLeaseColon.getText().toString().trim();
            //noinspection deprecation
            double deposit = MyUtils.valueOfDouble(totalDeposit, 0);
            //noinspection deprecation
            double lease = MyUtils.valueOfDouble(totalLease, 0);
            //如果金额小于等于0,直接提交.
            if (!((deposit + lease) > 0)) {
              volleyPostSubmit();
            } else {
              pay(deposit, lease);
            }
          }
        } else {
          ToastUtil.show("保存失败!");
        }
      }
    });
    //mActivity.setResult(Activity.RESULT_OK);
    //mActivity.finish();

  }

  private void volleyPostSubmit() {
    if (TextUtils.isEmpty(mId)) return;
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_LEASE_CHANGESTATUS);
    HashMap<String, String> params = new HashMap<>();
    params.put("ids", mId);
    params.put("memberCode", CurrentUser.newInstance(mActivity).getMemberCode());
    params.put("dataStatus", "submit");
    MyUtils.showDialogLoading(mActivity, R.string.submit);
    mActivity.volleyPost(url, params, new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {
        ToastUtil.show("提交失败");
      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        Base original = new Gson().fromJson(arg0, Base.class);
        if (original != null && original.getResult() == Base.SUCCESS) {
          ToastUtil.show("提交订单成功");
          mActivity.setResult(Activity.RESULT_OK);
          mActivity.finish();
        } else {
          ToastUtil.show("提交订单失败");
        }
      }
    });
  }

  @OnClick({ R.id.tv_leaseEquipmentDetail, R.id.tv_leaseDate }) public void onClick(View view) {
    if (view == null) return;
    switch (view.getId()) {
      case R.id.tv_leaseEquipmentDetail:
        if (TextUtils.isEmpty(orgCode)) {
          ToastUtil.show(R.string.hintSelectLeaseOrg);
          return;
        }
        SharedPreferencesUtil.setString(mActivity, SharedPreferencesUtil.KEY_LEASE_ORGCODE,
            orgCode);
        LeaseEquipmentListActivity.newInstance(this, mActivity, mId, status, REQUEST_EQUIP, true);
        break;
      case R.id.tv_leaseDate:
        //noinspection deprecation
        BaseYMDTimeDialogFragment dialog = BaseYMDTimeDialogFragment.newInstance(
            MyDateUtil.stringToDate(tvLeaseDate.getText().toString().trim()));
        dialog.setTargetFragment(this, REQUEST_DATE);
        dialog.show(mFm, "");
        break;
      default:
        break;
    }
  }

/*
    */

  /**
   * 根据type类别,初始化选择信息.
   *//*

    private void volleyPostByType(final int typeCode) {
        String url = ApiConst.getAbsoluteUrl(ApiConst.URL_DATA_DICT_TYPE);
        HashMap<String, String> params = new HashMap<>();
        switch (typeCode) {

            case REQUEST_TYPE:
                params.put("type", "workType");
                break;
            case REQUEST_OBJECT:
                //params.put("type","workObject");
                params.put("type", "workType");
                break;
            default:
                //ToastUtil.show("");
                return;
        }

        MyUtils.showDialogLoading(getActivity());
        mActivity.volleyPost(url, params, new VolleyResponse() {
            @Override
            public void onVolleyError(VolleyError arg0) {
                ToastUtil.show("获取失败");
            }

            @Override
            public void onVolleyResponse(String json) throws JSONException {
                //测试json数据.放在文件中.
                //基本信息验证.服务端返回默认是SelectOriginal格式的,解析成这个格式只是为了验证.
                //具体的使用还是要看具体的格式.


                SelectOriginal result = new Gson().fromJson(json, SelectOriginal.class);
                if (result == null || result.getResult() != Base.SUCCESS || result.getRows() == null || result.getRows().size() == 0) {
                    ToastUtil.show("获取失败");
                    return;
                }


                showDialog(result.getRows(), typeCode);
            }
        });


    }
*/
  //protected void showDialog(Date date, int typeCode) {
  //    DialogFragment dialog = BaseYMDTimeDialogFragment.newInstance(date);
  //    dialog.setTargetFragment(LeaseOrderUpdateFragment.this, typeCode);
  //    dialog.show(mFm, "");
  //}

  //protected void showDialog(final ArrayList<BaseSelectObject> rows, int typeCode) {
  //    BaseArrayDialogFragment dialog = SimpleArrayDialogFragment.newInstance(rows);
  //    if (dialog == null) return;
  //    dialog.setTargetFragment(this, typeCode);
  //    dialog.show(mFm, "");
  //
  //}
  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode != Activity.RESULT_OK) return;
    if (requestCode == REQUEST_PAY) {
      volleyPostSubmit();
    }
    if (requestCode == REQUEST_DATE && data != null) {
      Date date = (Date) data.getSerializableExtra(BaseTimeDialogFragment.EXTRA_DATE);
      //noinspection deprecation
      tvLeaseDate.setText(MyDateUtil.parseDateToString(date));
    }
    if (requestCode == REQUEST_EQUIP && data != null) {
      String deposit = data.getStringExtra(LeaseEquipmentListFragment.EXTRA_DEPOSIT);
      String leaseMoney = data.getStringExtra(LeaseEquipmentListFragment.EXTRA_LEASEMONEY);
      tvTotalDepositColon.setText(deposit);
      tvTotalLeaseColon.setText(leaseMoney);
    }
    if (requestCode == REQUEST_SYS_ORG && data != null) {
      CustomerDialog value =
          (CustomerDialog) data.getSerializableExtra(BaseNetworkDialogFragment.EXTRA_VALUE);
      slLeaseOrganizationColon.setTextContent(value.getName());
      orgCode = value.getId();
    }
    //if (requestCode == REQUEST_OPERATION_TIME && data != null) {
    //    mStartTime = (Date) data.getSerializableExtra(BaseTimeDialogFragment.EXTRA_DATE);
    //    //tvOperationTime.setText(DateFormat.format(MyDateUtil.TYPE_ALL, mStartTime));
    //}
    //if (requestCode == REQUEST_TYPE && data != null) {
    //    mType = (BaseSelectObject) data.getSerializableExtra(BaseArrayDialogFragment.EXTRA_VALUE);
    //    tvType.setText(mType.getName());
    //    //return;
    //}

  }

  private void pay(double deposit, double lease) {
    if (!((deposit + lease) > 0)) return;
    String id = "";
    String payMuch = "";
    String moneyType = "";
    if (deposit > 0) {
      id += UUID.randomUUID().toString();
      payMuch += String.valueOf(deposit);
      moneyType += PayAndBackParams.MONEY_TYPE_ANTECEDENT_FEE;
    }
    if (lease > 0) {
      id += getString(R.string.comma) + UUID.randomUUID().toString();
      payMuch += getString(R.string.comma) + String.valueOf(lease);
      moneyType += getString(R.string.comma) + PayAndBackParams.MONEY_TYPE_LEASE_FEE;
    }

    PayAndBackParams params = new PayAndBackParams();
    params.setId(id);
    params.setMainId(mId);
    params.setPayMuch(payMuch);
    params.setEditable(false);
    params.setMoneyType(moneyType);
    params.setBookOrderNo(mLeaseNo);
    params.setOrderType(PayAndBackParams.ORDER_TYPE_LEASE);
    PayAndBackActivity.newInstance(this, PayAndBackActivity.class, params, REQUEST_PAY);
  }
}
